package cn.edu.ctbu.datajpa04.webapi;

import cn.edu.ctbu.datajpa04.domain.Student;
import cn.edu.ctbu.datajpa04.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/webapi/student")
public class StudentRestController {

    @Autowired
    StudentService studentService;

    /**
     * 读取的url:/webapi/student/list
     * @return
     */
    @GetMapping("list")
    public  List<Student> searchStudent(String name){
        List<Student> students ;
        if(Objects.equals(name, "") || name == null) {
            students =studentService.findAll();
        } else{
            students =  studentService.findByName("%"+name+"%");
        }
        return students;
    }
    @GetMapping("list1")
    public List<Student> getAll(){
        List<Student> students = studentService.findAll();
        return students;
    }

    /**
     * 读取的url:/webapi/student/get/id
     * @return
     */
    @GetMapping("/get/{id}")
    public Student get(@PathVariable Integer id){

        Student student=studentService.findById(id);

        student.setPassword("");

        return student;
    }

    /**
     * 新增学生的方法，/webapi/student/insert
     * @param student
     * @return
     */
    @PostMapping("/insert")
    public Student insert(Student student){
        Student student1=studentService.insert(student);

        return student1;
    }

    /**
     * 更新学生方法，/webapi/student/update
     * @param student
     * @return
     */
    @PutMapping("/update")
    public Student update(Student student){
        //读旧数据
        Student oldStudent=studentService.findById(student.getId());

        if(StringUtils.isEmpty(student.getPassword())){
            //没有新密码，就是旧密码
            student.setPassword(oldStudent.getPassword());
        }
        studentService.update(student);

        return student;
    }
    /**
     * 删除学生方法，/webapi/student/delete
     * @param id
     * @return
     */
    @DeleteMapping("/delete/{id}")
    public void delete(@PathVariable Integer id){
        studentService.delete(id);

    }



}
